//
//  KDChildCollectController.m
//  WangJingApp
//
//  Created by 魏强 on 17/11/6.
//  Copyright © 2017年 KDTech. All rights reserved.
//

#import "KDChildCollectController.h"
#import "KDDetailSubscribController.h"
#import "KDCollectCell.h"
#import "KDCollectCellModel.h"
#import "KDReportController.h"
#import "KDPatrolgetReportParam.h"
#import "KDCollectRequestTool.h"
#import "KDGetFavorListParam.h"
#import "KDMoveFavorParam.h"
#import "KDTabBarController.h"
#import "KDCollectTypeListController.h"
#import "KGDislikeView.h"
@interface KDChildCollectController ()<UITableViewDelegate,UITableViewDataSource, KDDetailSubscribControllerDelegate,KDReportControllerDelegate,KDCollectCellDelegate>

/**  <#Description#> */
@property (nonatomic, weak) UITableView *currentTabV;

/**  所有数据汇总 */
@property (nonatomic, strong) NSArray *infoArr;
/**
 *  加载第几页
 */
@property (nonatomic, copy) NSString *page;
@property (nonatomic, retain) NSDateFormatter *fmt;

@end

@implementation KDChildCollectController
#pragma mark - 懒加载区
- (NSDateFormatter *)fmt
{
    if (!_fmt) {
        _fmt = [[NSDateFormatter alloc]init];
        _fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];;
        _fmt.dateFormat = @"YYYY-MM-dd HH:mm:ss";
    }
    return _fmt;
}
- (NSString *)page
{
    if (!_page) {
        _page = @"1";
    }
    return _page;
}
- (NSArray *)infoArr
{
    if (!_infoArr) {
        _infoArr = [NSArray new];
    }
    return _infoArr;
}

#pragma mark - 生命周期区
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    [self setUpTableView];
}
#pragma mark - 板块布置区
- (void)setUpTableView
{
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0  , 0, screenW, self.view.height -88) style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tag = 1000;
    tableView.tableFooterView = [UIView new];
    tableView.separatorColor = BackGroundColor;
    tableView.backgroundColor = BackGroundColor;
    tableView.rowHeight = Cell_h;
    if (!iOS7) {
        tableView.estimatedRowHeight = Cell_h;
    }
    self.currentTabV = tableView;
    [self.view addSubview:tableView];
    UINib *xib =[UINib nibWithNibName:@"KDCollectCell" bundle:nil] ;
    
    [tableView registerNib:xib forCellReuseIdentifier:@"KDCollectCell"];
    tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadDetailData)];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreDetailData)];
    [footer setTitle:@"" forState:MJRefreshStateIdle];
    // 设置footer
    self.currentTabV.footer = footer;
    [self.currentTabV.header beginRefreshing];
}
#pragma mark - 事件点击区

#pragma mark - 网络请求区

- (void)loadDetailData{
    WS(ws);
    KDGetFavorListParam *param = [[KDGetFavorListParam alloc]init];
    self.page = @"1";
    param.page = self.page;
    param.limit = @"20";
    param.type_id = [NSString stringWithFormat:@"%ld",self.model.type_id];
    [KDCollectRequestTool getFavorListWithParam:param success:^(KDBaseResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            ws.infoArr = [KDCollectCellModel objectArrayWithKeyValuesArray:responseObejct.data[@"data"]];
            [ws.currentTabV.header endRefreshing];
            [ws.currentTabV reloadData];
        }else if ([responseObejct.code isEqualToString:@"E040110000001"]){
            [ws.currentTabV.header endRefreshing];
            [ws.navigationController dismissViewControllerAnimated:NO completion:^{
                KDNewfeatureController *new = [[KDNewfeatureController alloc]init];
                __block KDTabBarController*ctr = (KDTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                [UIApplication sharedApplication].keyWindow.rootViewController = new;
                [ctr removeObserver];
                [ctr removeFromParentViewController];
                ctr = nil;
            }];
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
            [ws.currentTabV.header endRefreshing];
        }

    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误！" maskType:SVProgressHUDMaskTypeGradient];
        [ws.currentTabV.header endRefreshing];
        KDLog(@"%@",error);

    }];
}

- (void)loadMoreDetailData{
    WS(ws);
    KDGetFavorListParam *param = [[KDGetFavorListParam alloc]init];
    self.page = [NSString stringWithFormat:@"%ld", self.page.integerValue +1];
    param.page = self.page;

    param.limit = @"20";
    param.type_id = [NSString stringWithFormat:@"%ld",self.model.type_id];
    [KDCollectRequestTool getFavorListWithParam:param success:^(KDBaseResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            NSArray *arr1 = [KDCollectCellModel objectArrayWithKeyValuesArray:responseObejct.data[@"data"]];
            if (arr1.count) {
                NSMutableArray *arr = [NSMutableArray arrayWithArray:ws.infoArr];
                [arr addObjectsFromArray:arr1];
                ws.infoArr = arr;
                [ws.currentTabV.footer endRefreshing];
                [ws.currentTabV reloadData];
            }else{
                [ws.currentTabV.footer noticeNoMoreData];
            }
            
            
            [ws.currentTabV reloadData];
        }else if ([responseObejct.code isEqualToString:@"E040110000001"]){
            [ws.currentTabV.footer endRefreshing];
            [ws.navigationController dismissViewControllerAnimated:NO completion:^{
                KDNewfeatureController *new = [[KDNewfeatureController alloc]init];
                __block KDTabBarController*ctr = (KDTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                [UIApplication sharedApplication].keyWindow.rootViewController = new;
                [ctr removeObserver];
                [ctr removeFromParentViewController];
                ctr = nil;
            }];
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
            [ws.currentTabV.footer endRefreshing];
        }
        
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误！" maskType:SVProgressHUDMaskTypeGradient];
        [ws.currentTabV.footer endRefreshing];
        KDLog(@"%@",error);
        
    }];
}

/**
 *  通过ID，请求获取一个本信息的所有细节
 *
 *  @param ID 信息ID
 */
- (void)getNewsModelWithID:(NSString *)ID success:(void (^)(KDSubscribCellModel *model))success{
    
    KDMoveFavorParam *param = [[KDMoveFavorParam alloc]init];
    param.ID = ID;
    [SVProgressHUD showWithStatus:@"加载中…" maskType:SVProgressHUDMaskTypeGradient];
    [KDCollectRequestTool getNewsWithParam:param success:^(KDBaseResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
           KDSubscribCellModel * model= [KDSubscribCellModel objectWithKeyValues:responseObejct.data];
            [SVProgressHUD dismiss];
            if (model) {
                success(model);
            }else{
                [SVProgressHUD showInfoWithStatus:@"未查询到数据" maskType:SVProgressHUDMaskTypeGradient];
            }
            
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误!" maskType:SVProgressHUDMaskTypeGradient];
    }];
}
#pragma mark - 通知接收区

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.infoArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KDCollectCell *cell = [KDCollectCell cellWithTableView:tableView];
    //    KDLog(@"waimian%d", indexPath.row);
    cell.delegate = self;
    if (tableView == self.currentTabV)
    {
        cell.delegate = self;
        if (self.infoArr.count != 0)
        {
            cell.model = self.infoArr[indexPath.row];
        }
        return cell;
    }else{
        return cell;
    }
}
/**
 *  cell被点击了
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.currentTabV) {
        if (self.infoArr.count == 0) {
            return;
        }
        KDCollectCell *cell = (KDCollectCell *)[tableView cellForRowAtIndexPath:indexPath];
        NSMutableArray *arr = [NSMutableArray arrayWithArray:self.infoArr];
        [arr replaceObjectAtIndex:indexPath.row withObject:cell.model];
        self.infoArr = arr;
        WS(ws);
        [self getNewsModelWithID:[NSString stringWithFormat:@"%ld",cell.model.info_id] success:^(KDSubscribCellModel *model) {
            KDDetailSubscribController *singleCtrl = [[KDDetailSubscribController alloc]init];
            singleCtrl.delegate = ws;
            model.isCollection = YES;
            singleCtrl.model = model;
            
//            self.hidesBottomBarWhenPushed = YES;
            [ws.navigationController pushViewController:singleCtrl animated:YES];
//            self.hidesBottomBarWhenPushed = NO;
        }];
        
        
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - KDCollectCellDelegate

/**
 *  收藏按钮被点击了
 */
- (void)subscribCell:(KDCollectCell *)cell moveBtnClick:(UIButton *)moveBtn{
    KDCollectTypeListController *ctr = [[KDCollectTypeListController alloc]init];
    ctr.collectCellModel = cell.model;
    [ctr moveSuccess:^{
        [self.currentTabV.header beginRefreshing];
    }];
    [self.navigationController pushViewController:ctr animated:YES];
}

/**
 *  上报按钮被点击了
 */
- (void)subscribCell:(KDCollectCell *)cell reportBtnClick:(UIButton *)reportBtn{
    WS(ws);
    [self getNewsModelWithID:[NSString stringWithFormat:@"%ld",cell.model.info_id] success:^(KDSubscribCellModel *model) {
        KDReportController *reportCtrl = [[KDReportController alloc]init];
        KDPatrolgetReportParam *param = [[KDPatrolgetReportParam alloc]init];
        param.url = model.craw_url;
        param.info_title = model.craw_title;
        param.info_content = model.craw_content;
        param.website_type = model.site_type;
        param.website_name = model.site_name;
        reportCtrl.param = param;
//        reportCtrl.type = 1;
        reportCtrl.delegate = ws;
        [ws.navigationController pushViewController:reportCtrl animated:YES];
    }];
   
}

/**
 *  删除按钮被点击了
 */
- (void)subscribCell:(KDCollectCell *)cell deleteBtnClick:(UIButton *)deleteBtn{
    WS(ws);
    NSMutableArray *arr = [NSMutableArray arrayWithArray:self.infoArr];
    NSIndexPath *ip = [self.currentTabV indexPathForCell:cell];

    [KGDislikeView showFromView:cell dislikeBlock:^(KGDislikeView *dislikeView) {
        KDFavorParam *param = [[KDFavorParam alloc]init];
         param.info_id = [NSString stringWithFormat:@"%ld",cell.model.info_id];
        [KDCollectRequestTool cancelFavorMsgWithParam:param success:^(KDBaseResult *responseObejct) {
            if ([responseObejct.code isEqualToString:@"1"]) {
                [arr removeObjectAtIndex:ip.row];
                ws.infoArr = arr;
                [ws.currentTabV deleteRowsAtIndexPaths:@[ip]withRowAnimation:UITableViewRowAnimationAutomatic];
            }else{
                [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
            }

        } failure:^(NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"网络错误!" maskType:SVProgressHUDMaskTypeGradient];

        }];
    }];
}
@end
